package com.zs.toolbox.web2j.system.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.toolbox.web2j.common.exception.WtExceptions;
import com.zs.toolbox.web2j.db.config.OnlyReadDbOperation;
import com.zs.toolbox.web2j.system.core.entity.WtPermissionEntity;
import com.zs.toolbox.web2j.system.core.entity.WtRolePermissionEntity;
import com.zs.toolbox.web2j.system.core.mapper.other.WtPermissionMapper;
import com.zs.toolbox.web2j.system.core.service.WtPermissionService;
import com.zs.toolbox.web2j.system.core.service.WtRolePermissionService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author eric.zhang
 * @since 2018-09-26
 */
@Service
public class WtPermissionServiceImpl extends ServiceImpl<WtPermissionMapper, WtPermissionEntity> implements WtPermissionService {
    @Autowired
    WtRolePermissionService wtRolePermissionService;

    @Override
    @OnlyReadDbOperation
    public List<WtPermissionEntity> selectRolePermissionsByRoleIds(List<Long> roleIds) {

        List<WtRolePermissionEntity> rolePermissionEntities = wtRolePermissionService
                .list(new LambdaQueryWrapper<WtRolePermissionEntity>()
                        .in(WtRolePermissionEntity::getRoleId, roleIds));

        if (CollectionUtils.isNotEmpty(rolePermissionEntities)) {
            List<WtPermissionEntity> wtPermissionEntities = baseMapper.selectBatchIds(
                    rolePermissionEntities.stream().map(WtRolePermissionEntity::getPermissionId).collect(Collectors.toList())
            );
            return wtPermissionEntities;
        } else {
            return ListUtils.EMPTY_LIST;
        }

    }

    @Override
    public boolean save(WtPermissionEntity entity) {
        if (StringUtils.isNotBlank(entity.getPermissionCode())) {
            WtPermissionEntity existEntity = getOne(new LambdaQueryWrapper<WtPermissionEntity>()
                    .eq(WtPermissionEntity::getPermissionCode, entity.getPermissionCode()));
            if (existEntity != null && (!existEntity.getId().equals(entity.getId()))) {
                throw WtExceptions.E_USE_PERMISSION_EXIST;
            }
        }
        return super.save(entity);
    }
}
